package com.cskaoyan.service.system;

import com.cskaoyan.bean.BasePageInfo;
import com.cskaoyan.bean.bo.sysytem.RolePermissionsPostBo;
import com.cskaoyan.bean.po.adminpo.MarketAdmin;
import com.cskaoyan.bean.po.adminpo.MarketAdminExample;
import com.cskaoyan.bean.po.ohter.*;
import com.cskaoyan.bean.vo.system.*;
import com.cskaoyan.mapper.MarketAdminMapper;
import com.cskaoyan.mapper.MarketPermissionMapper;
import com.cskaoyan.mapper.MarketPermissionSystemMapper;
import com.cskaoyan.mapper.MarketRoleMapper;
import com.cskaoyan.util.beanutils.BeanUtil;
import com.cskaoyan.util.common.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @auther zk
 * @date 2022/7/16 16:50
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    MarketRoleMapper marketRoleMapper;
    @Autowired
    MarketPermissionMapper marketPermissionMapper;
    @Autowired
    MarketPermissionSystemMapper marketPermissionSystemMapper;
    @Autowired
    MarketAdminMapper marketAdminMapper;

    @Override
    public RoleListVo roleList(BasePageInfo info, String name) {
        PageHelper.startPage(info.getPage(), info.getLimit());
        name = StringUtils.isEmpty(name) ? "%" : ("%" + name + "%");
        List<RoleInfo> roleInfos = marketRoleMapper.selectByName(name, info.getSort(), info.getOrder());
        PageInfo<RoleInfo> pageInfo = new PageInfo<>(roleInfos);
        return new RoleListVo((int) pageInfo.getTotal(), pageInfo.getPages(), info.getLimit(), info.getPage(), roleInfos);
    }

    @Override
    @Transactional
    public RoleCreateVo roleCreate(String name, String desc) {
        MarketRole marketRole = new MarketRole();
        marketRole.setName(name);
        marketRole.setDesc(desc);
        marketRole.setEnabled(true);
        marketRole.setAddTime(new Date(System.currentTimeMillis()));
        marketRole.setUpdateTime(new Date(System.currentTimeMillis()));
        marketRole.setDeleted(false);
        try {
            marketRoleMapper.insert(marketRole);
        } catch (Exception e) {
            return null;
        }
        RoleCreateVo roleCreateVo = new RoleCreateVo();
        BeanUtil.copyBean(marketRole, roleCreateVo);
        return roleCreateVo;
    }

    @Override
    public Integer roleUpdate(Map map) {
        MarketRoleExample example = new MarketRoleExample();
        MarketRoleExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo((Integer) map.get("id"));
        MarketRole marketRole = new MarketRole();
        marketRole.setName((String) map.get("name"));
        marketRole.setDesc((String) map.get("desc"));
        marketRole.setUpdateTime(new Date(System.currentTimeMillis()));
        try {
            marketRoleMapper.updateByExampleSelective(marketRole, example);
        } catch (Exception e) {
            return null;
        }
        return 1;
    }

    @Override
    public RolePermissions0GetVo getRolePermissions(Integer roleId) {

        MarketPermissionSystemExample example1 = new MarketPermissionSystemExample();
        List<MarketPermissionSystem> marketPermissionSystemList = marketPermissionSystemMapper.selectByExample(example1);
        List<RolePermissions1ModuleInfo> systemPermissions = new ArrayList<>();
        // 遍历查询出的所有可授权接口
        outer:
        for (MarketPermissionSystem mps : marketPermissionSystemList) {

            RolePermissions1ModuleInfo p1 = new RolePermissions1ModuleInfo();
            RolePermissions2CategoryInfo p2 = new RolePermissions2CategoryInfo();
            RolePermissions3InterfaceInfo p3 = new RolePermissions3InterfaceInfo();

            p3.setId(mps.getPort());
            p3.setLabel(mps.getLable());
            p3.setApi(mps.getApi());

            p2.setId(mps.getClassify());
            p2.setLabel(mps.getClassify());
            List<RolePermissions3InterfaceInfo> l3 = new ArrayList<>();
            l3.add(p3);
            p2.setChildren(l3);

            p1.setId(mps.getModule());
            p1.setLabel(mps.getModule());
            List<RolePermissions2CategoryInfo> l2 = new ArrayList<>();
            l2.add(p2);
            p1.setChildren(l2);

            for (RolePermissions1ModuleInfo systemPermission : systemPermissions) {
                if (mps.getModule().equals(systemPermission.getId())) {
                    // 包含该模块，遍历模块中的所有类目
                    for (RolePermissions2CategoryInfo child : systemPermission.getChildren()) {
                        if (mps.getClassify().equals(child.getId())) {
                            // 包含该类目，在该类目下的接口列表中添加一个接口
                            child.getChildren().add(p3);
                            continue outer;
                        }
                    }
                    // 不包含该类目，在该模块中添加类目以及接口
                    systemPermission.getChildren().add(p2);
                    continue outer;
                }
            }
            // 不包含该模块
            systemPermissions.add(p1);
        }

        MarketPermissionExample example2 = new MarketPermissionExample();
        MarketPermissionExample.Criteria criteria = example2.createCriteria();
        criteria.andRoleIdEqualTo(roleId);
        List<MarketPermission> marketPermissionList = marketPermissionMapper.selectByExample(example2);
        List<String> assignedPermissions = new ArrayList<>();
        for (MarketPermission mp : marketPermissionList) {
            assignedPermissions.add(mp.getPermission());
        }

        RolePermissions0GetVo vo = new RolePermissions0GetVo();
        vo.setSystemPermissions(systemPermissions);
        vo.setAssignedPermissions(assignedPermissions);
        return vo;
    }

    @Override
    @Transactional
    public Integer postRolePermissions(RolePermissionsPostBo bo) {

        try {
            MarketPermissionExample example1 = new MarketPermissionExample();
            MarketPermissionExample.Criteria criteria1 = example1.createCriteria();
            criteria1.andRoleIdEqualTo(bo.getRoleId());

            List<MarketPermission> oldPermissions = marketPermissionMapper.selectByExample(example1);

            marketPermissionMapper.deleteByExample(example1);

            List<String> op = new ArrayList<>();
            HashMap<String, MarketPermission> map = new HashMap<>();
            for (MarketPermission oldPermission : oldPermissions) {
                map.put(oldPermission.getPermission(), oldPermission);
            }

            for (String permission : bo.getPermissions()) {
                MarketPermission row = new MarketPermission();
                row.setRoleId(bo.getRoleId());
                row.setPermission(permission);
                row.setDeleted(false);
                if (map.containsKey(permission)) {
                    row.setAddTime(map.get(permission).getAddTime());
                } else {
                    row.setAddTime(new Date(System.currentTimeMillis()));
                }
                row.setUpdateTime(new Date(System.currentTimeMillis()));

                marketPermissionMapper.insertSelective(row);
            }
        } catch (Exception e) {
            return 0;
        }

        return 1;
    }

    @Override
    public int roleDelete(RoleInfo roleInfo) {
        // 查管理员表，看是否有该角色的管理员存在,若存在，返回642
        MarketAdminExample example1 = new MarketAdminExample();
        List<MarketAdmin> admins = marketAdminMapper.selectByExample(example1);
        for (MarketAdmin admin : admins) {
            Integer[] roleIds = admin.getRoleIds();
            for (Integer roleId : roleIds) {
                if (roleId.equals(roleInfo.getId())) {
                    return 642;
                }
            }
        }
        // 若不存在，逻辑删除该角色，返回0
        MarketRoleExample example2 = new MarketRoleExample();
        MarketRoleExample.Criteria criteria = example2.createCriteria();
        criteria.andIdEqualTo(roleInfo.getId());
        MarketRole marketRole = new MarketRole();
        marketRole.setDeleted(true);
        marketRoleMapper.updateByExampleSelective(marketRole, example2);
        return 0;
    }

    @Override
    public RoleOptionsVo roleOptions() {
        MarketRoleExample example = new MarketRoleExample();
        MarketRoleExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedNotEqualTo(true);
        List<MarketRole> marketRoles = marketRoleMapper.selectByExample(example);
        List<RoleOptions> roleOptions = new ArrayList<>();
        for (MarketRole marketRole : marketRoles) {
            RoleOptions ro = new RoleOptions();
            BeanUtil.copyBean(marketRole, ro);
            roleOptions.add(ro);
        }
        RoleOptionsVo roleOptionsVo = new RoleOptionsVo();
        roleOptionsVo.setTotal(marketRoles.size());
        roleOptionsVo.setPages(marketRoles.size() / 20 == 0 ? marketRoles.size() / 20 : marketRoles.size() / 20 + 1);
        roleOptionsVo.setLimit(20);
        roleOptionsVo.setPage(1);
        roleOptionsVo.setList(roleOptions);
        return roleOptionsVo;
    }
}
